package com.test.test;

class MyLinkedList {

    int size;
    ListNode head;



    public MyLinkedList() {

    }

    public int get(int index) {
        ListNode node = head;
        for (int i = 0; i <= index; i++) {
            if (i == index) {
                return node.val;
            } else if (node.next != null) {
                node = node.next;
            } else {
                return -1;
            }
        }
        return node.val;
    }

    public void addAtHead(int val) {
        ListNode node = head;
        ListNode oldNode = new ListNode(node.val);
        oldNode.next = node.next;
        node.val = val;
        node.next = oldNode;
    }

    public void addAtTail(int val) {
        ListNode node = head;
        while (node.next != null) {
            node = node.next;
        }
        node.next = new ListNode(val);
    }

    public void addAtIndex(int index, int val) {
        ListNode node = head;
        if (node.next == null) {
            addAtTail(val);
            return;
        }
        for (int i = 0; i < index; i++) {
            node = node.next;
            if (node == null) {
                return;
            }
        }
        ListNode indexNode = new ListNode(val);
        indexNode.next = node.next;
        node.next = indexNode;
    }

    public void deleteAtIndex(int index) {
        ListNode node = head;
        for (int i = 0; i < index - 1; i++) {
            node = node.next;
            if (node == null) {
                return;
            }
        }
        node.next = node.next.next;

    }


}
class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}


/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */
